package com.etonenet.service.system;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.etonenet.entity.system.Url;
import com.etonenet.entity.system.UrlAction;
import com.etonenet.repository.system.UrlActionRepository;
import com.etonenet.repository.system.UrlRepository;

import esms.etonenet.boss1069.enums.LogicStat;
import esms.etonenet.boss1069.web.UrlConstants;

@Service
public class UrlService {

	@Autowired
	private UrlActionRepository urlActionEm;

	@Resource
	private UrlRepository urlEm;

	// @PostConstruct
	private void initUrl() throws IllegalArgumentException, IllegalAccessException {
		for (Field f : UrlConstants.class.getFields()) {
			String url = (String) f.get(f.getName());
			UrlAction ua = urlActionEm.findByUrlAndLogicStat(url, LogicStat.NORMAL.getValue());
			if (ua == null) {
				ua = new UrlAction();
				ua.setLogicStat(LogicStat.NORMAL.getValue());
				ua.setUrl(url);

				urlActionEm.save(ua);
			}

		}
	}

	@PostConstruct
	public void initUrl2() throws IllegalArgumentException, IllegalAccessException {

		// 获得表中所有url
		Map<String, Url> urls = new HashMap<>();
		for (Url url : urlEm.findAll())
			urls.put(url.getUrl(), url);

		List<String> constantsUrls = new ArrayList<>();
		for (Field f : UrlConstants.class.getFields()) {
			String u = (String) f.get(f.getName());

			constantsUrls.add(u);
		}

		// 增加新的url
		for (String u : constantsUrls) {
			if (!urls.containsKey(u)) {
				Url url = urlEm.findByUrl(u);
				if (url == null) {
					url = new Url();
					url.setUrl(u);

					urlEm.save(url);
				}
			}
		}

		// 更新constantsUrls不存在数据库存在的url状态
		for (String u : urls.keySet()) {
			if (!constantsUrls.contains(u)) {
				Url url = urls.get(u);
				url.setIsExist(1);

				urlEm.save(url);
			}
		}
	}

	public Page<Url> page(PageRequest pageRequest, Specification<Url> spec) {

		return urlEm.findAll(spec, pageRequest);
	}

	public void del(List<Url> data) {

		urlEm.delete(data);
	}

	public List<Object[]> auto(String term) {

		return urlEm.auto(term);
	}
}
